import os
import time
import tkinter as tk# 导入 Tkinter 库
import traceback
import tkinter.filedialog
from Basic.base_01_LOG import Log
from Basic.base_03_openpyxlExcel import OpenpyxlExcel
from UiniTest.HTMLReportTest import HTMLReportTest

#tk.N 上  S下  W左 E右
from Basic.base_04_read_ini import ReadIni
from Basic import basic_path


class UiTest(tk.Frame):
    """docstring for Application"""
    def __init__(self,master=None):
        if master ==None:
           master=tk.Tk()  # 创建窗口对象
        super().__init__(master)
        # HTMLReportTest.__init__(self)
        # self.datatime = time.strftime('%Y-%m-%d', time.localtime(time.time()))

        # self.ini_path = r'%s\config.ini' % os.getcwd()

        self.filename = "%s\Conf\LZ_Element.xlsx" % (os.getcwd())
        self.sheetname = '6101'

        self.testcase = self.get_Case(self.filename, self.sheetname)
        self.skipcase = []
        self.operatecase = self.testcase

        # TK初始化
        self.master=master
        self.master.title('自动化测试')
        self.master.geometry("630x600")
        self.fram1 = tk.Frame(self.master, bd=15, bg='yellow')
        self.fram2 = tk.Frame(self.master, bd=15)
        self.fram3 = tk.Frame(self.master, bd=15,bg='yellow')
        self.fram1.pack()
        self.fram3.pack()
        self.fram2.pack()

        self.var_selectcase = []  #用例复选框状态列表
        self.caselist_checkbtn = []# 用例复选框列表
        self.start_btn = None

        self.fram_select_excel()
        self.fram_select_case()
        self.fram_star_test()
        self.mainloop()

    def get_Case(self,filename,sheetname):
        # CASE初始化
        #判断文件存在
        case = []  # 所有用例
        if os.path.exists(filename):
            ex = OpenpyxlExcel(filename=filename, sheetname=sheetname)
            case = ex.get_CaseMoudle_Name()
        return case

    """布局1：选择测试用例文件"""
    def fram_select_excel(self):
        '''选择测试用例文件'''
        # 添加标签提示
        lab = tk.Label(self.fram1, text='测试用例路径：')
        lab.grid(row=0,column=0)
        #选择文件输出框
        self.excel_path = tk.StringVar()
        edit = tk.Entry(self.fram1,textvariable=self.excel_path,bd =5,width=60)
        edit.grid(row=0,column=1,pady=5)        #显示控件
        self.excel_path.set(self.filename)      #设置默认值
        #选择文件按钮，点击打开选择文件窗口
        pathBtn = tk.Button(self.fram1, text="选择文件", command=lambda: self.select_excelpath_command())
        pathBtn.grid(row=0, column=2,padx=5)

        '''选择测试用例工作表'''
        # 添加标签提示
        lab2 = tk.Label(self.fram1, text='测试用例工作表：')
        lab2.grid(row=1, column=0)
        #添加工作表输入框
        self.var_sheetEntry = tk.StringVar()
        edit2 = tk.Entry(self.fram1, textvariable=self.var_sheetEntry,bd=5, width=60)
        edit2.grid(row=1, column=1, pady=5)
        self.var_sheetEntry.set(self.sheetname)#设置默认值
        #确定按钮，点击显示用例选择界面
        # self.var_selectCasebtn = tk.StringVar()
        pathBtn2 = tk.Button(self.fram1, text="确定", command=lambda:self.selectsheet_command())
        pathBtn2.grid(row=1, column=2, padx=5)
        '''测试用例模块显示'''
        #测试用例模块标签
        lab3 = tk.Label(self.fram1,text="测试用例模块:")
        lab3.grid(row=2,column=0)
        # 测试用例模块显示
        self.var_caseMes = tk.StringVar()
        self.message = tk.Message(self.fram1,textvariable=self.var_caseMes,text=self.var_caseMes,width=500)
        self.message.grid(row=2,column=1,columnspan=3,pady=5)
        if os.path.exists(self.filename):
            self.var_caseMes.set(self.testcase)
            self.message.configure(fg="black")
        else:
            self.var_caseMes.set('测试用例路径不存在! %s'%self.filename)
            self.message.configure(fg="red")

    """布局2：测试用例选择"""
    def fram_select_case(self):
        # 添加标签提示
        lab = tk.Label(self.fram2, text='请选择要执行的用例:', fg='red')
        lab.grid(row=0, column=0, sticky=tk.W)
        # lab.pack()
        # 添加用例选择复选框
        self.case_checkbutton()

    """布局3：开始测试按钮"""
    def fram_star_test(self):
        #开始测试按钮
        self.start_btn = tk.Button(self.fram3, text='开始测试',bd=5,width=30,command=lambda: self.startTest_command())
        self.start_btn.pack(pady=10)
        # 全选按钮
        # var_selectall = tk.IntVar()  # tk.IntVar() 记录复选框variable数值
        self.selectall_checkbtn = tk.Checkbutton(self.fram3, text='全选',command=lambda: self.Checkbutton_command())  # 添加全选复选框
        self.selectall_checkbtn.pack()  # 显示在TK控件
        self.selectall_checkbtn.select()



    #选择用例确定按钮，点击后更新测试用例模块显示和选择模块区
    def selectsheet_command(self):
        self.start_btn.config(state=tk.NORMAL) #NORMAL 常态，ACTIVE 激活，DISABLED 无效
        self.fram2.destroy()  # 清除布局显示
        self.fram3.forget()
        try:
            self.filename = self.excel_path.get()
            self.sheetname = self.var_sheetEntry.get()
            self.testcase= self.get_Case(self.filename,self.sheetname)
            if os.path.exists(self.filename):
                self.var_caseMes.set(self.testcase)
                self.message.configure(fg="black")
            else:
                self.var_caseMes.set('测试用例路径不存在! %s'%self.filename)
                self.message.configure(fg="red")

            #更新用例选择复选框
            self.fram3.pack()
            self.fram2 = tk.Frame(self.master, bd=15)
            self.fram_select_case() #重新加载
            self.fram2.pack()
        except Exception as e:
            # error_labv = 'ERROE: %s'%e
            self.message.configure(fg="red")
            self.var_caseMes.set('测试用例工作表不存在! %s'% (self.sheetname))
            print(traceback.format_exc())

    def select_excelpath_command(self):
        # 选择文件path_接收文件地址
        secpath = tkinter.filedialog.askopenfilename()
        # 通过replace函数替换绝对文件地址中的/来使文件可被程序读取
        # 注意：\\转义后为\，所以\\\\转义后为\\
        secpath = secpath.replace("/", "\\\\")
        # path设置path_的值
        if secpath != '':
            self.excel_path.set(secpath) #改变控件变量
            self.filename=secpath



    def case_checkbutton(self):
        flagR = 0
        flagC = 0
        # 显示复选框按钮
        self.var_selectcase = []  #用例复选框状态列表
        self.caselist_checkbtn = []# 用例复选框列表
        for i in range(len(self.testcase)):
            self.var_selectcase.append(tk.IntVar())  # tk.IntVar() 记录复选框variable数值
            selectcase_checkbtn = tk.Checkbutton(self.fram2, variable=self.var_selectcase[i], text=self.testcase[i],command=lambda:self.casebtn_command() )  # 添加复选框
            selectcase_checkbtn.select()  # 勾选复选框
            if i % 6 == 0:
                flagR += 1
                flagC = 0
            selectcase_checkbtn.grid(row=flagR, column=flagC, sticky=tk.W)  # 显示在TK控件
            # selectcase_checkbtn.pack()
            flagC += 1
            self.caselist_checkbtn.append(selectcase_checkbtn)  # 将实例化的复选框添加进集合

    def casebtn_command(self):
        #复选框按钮状态改变时，全选按钮的状态也随之改变
        # self.selectall_checkbtn.toggle()
        pass

    # 当点击全选按钮时执行程序，切换所有复选框状态
    def Checkbutton_command(self):
        for c in self.caselist_checkbtn:
            c.toggle()  # 切换复选框勾选状态


    # 当按下开始测试按钮时，读取要执行的用例，并执行测试
    def startTest_command(self):
        self.start_btn.config(state=tk.DISABLED)#按钮置灰色
        #读取要执行的用例
        for i in range(len(self.var_selectcase)):
            if self.var_selectcase[i].get() == 1:
                self.operatecase.append(self.testcase[i])
        print('已选择测试用例%s ' % self.operatecase)

        for i in range(len(self.var_selectcase)):
            if self.var_selectcase[i].get() == 0:
                self.skipcase.append(self.testcase[i])
        print('跳过的测试用例%s ' % self.skipcase)
        print('开始测试')
        self.fram2.destroy()
        self.master.destroy()

        self.daytime = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        self.datatime = time.strftime('%Y-%m-%d %H.%M.%S', time.localtime(time.time()))
        dictpath = self.get_dictpath()
        self.set_ini(dictpath)
        HTMLReportTest().HTMLtest_main(dictpath,self.datatime,"LZ_04_ddt")#执行测试




    def set_ini(self,dictpath,):
        confini_path = dictpath["confini_path"]
        readini = ReadIni(ini_path=confini_path)
        sectionList = ['excel', 'casemoudel',  'path','time','error']
        for sec in sectionList:
            readini.add_section(sec)
        readini.set_value('excel','filename',self.filename)
        readini.set_value('excel', 'sheetname', self.sheetname)
        skipcase = ' '.join(self.skipcase) #列表转换字符串
        operatecase = ' '.join(self.operatecase)#列表转换字符串
        readini.set_value('casemoudel', 'skipcase', skipcase)
        readini.set_value('casemoudel', 'operatecase',operatecase)
        readini.set_value('path', 'package_path', dictpath["package_path"])
        readini.set_value('path', 'basic_path', dictpath["basic_path"])
        readini.set_value('path', 'Conf_path', dictpath["Conf_path"])
        readini.set_value('path', 'confini_path', dictpath["confini_path"])
        readini.set_value('path', 'FindElement_path', dictpath["FindElement_path"])
        readini.set_value('path', 'UiniTest_path', dictpath["UiniTest_path"])
        readini.set_value('path', 'log_path', dictpath["log_path"])
        readini.set_value('path', 'code_path', dictpath["code_path"])
        readini.set_value('time', 'time1','10')
        readini.set_value('time', 'time2', '1')
        readini.set_value('time', 'datatime', self.datatime)
        readini.set_value('time', 'daytime', self.daytime)
        readini.set_value('error', 'error_log', '')


    def get_dictpath(self):
        path_dict = {"package_path": os.getcwd(),
                     "basic_path": os.path.join(os.getcwd(), 'Basic'),
                     "Conf_path":os.path.join(os.getcwd(), 'Conf'),
                     "confini_path": os.path.join(os.getcwd(), 'Conf', "config.ini"),
                     "FindElement_path":os.path.join(os.getcwd(), 'FindElement'),
                     "UiniTest_path":os.path.join(os.getcwd(), 'UiniTest'),
                     "log_path":os.path.join(os.getcwd(), 'Logs'),
                     "code_path":os.path.join(os.getcwd(), 'Logs',"getcode.jpg"),
                     "datatime":time.strftime('%Y-%m-%d %H.%M.%S', time.localtime(time.time())),
                     "daytime":time.strftime('%Y-%m-%d', time.localtime(time.time()))
        }
        if not os.path.exists(os.path.join(os.getcwd(), 'Logs')):
            os.makedirs(os.path.join(os.getcwd(), 'Logs'))
        return path_dict


if __name__ == "__main__":
    UiTest()
    pass
